package com.fast.develop.dm.integration.orm;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.develop.dm.core.data.Page;
import com.fast.develop.dm.core.data.Pageable;
import com.fast.develop.dm.core.persistence.DomainModelManager;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author 莫寅
 * @createTime 2022-06-05 05:09
 * @desc：
 */
public class DomainModelSessionManager implements DomainModelManager {

    private Session session;

    public DomainModelSessionManager(Session session) {
        this.session = session;
    }

    @Override
    public List list(String model){
        String hql = StrUtil.format("from {}", model);
        Query query = session.createQuery(hql);
        return query.getResultList();
    }

    @Override
    public Page page(String model, Pageable pageable){

        String hql = StrUtil.format("from {}", model);
        Query query = session.createQuery(hql);
        query.setFirstResult((pageable.getPageNumber()-1) * pageable.getPageSize());
        query.setMaxResults(pageable.getPageNumber() * pageable.getPageSize());


        Query countQuery = session.createQuery(StrUtil.format("select count(*) from {}", model));
        Number count = (Number)countQuery.uniqueResult();

        int userCount = count.intValue();

        List list = query.getResultList();

        Page page = new Page(userCount, list, pageable);
        return page;
    }

    @Override
    public Object get(String model, Serializable serializable){
        return session.get(model, serializable);
    }


    @Override
    public Serializable create(String model, Map map){
        Transaction transaction = session.beginTransaction();
        try{
            Serializable serializable = session.save(model, map);

            transaction.commit();
            return serializable;
        }catch (Exception e){
            transaction.rollback();
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void update(String model, String id, Map map){
        Transaction transaction = session.beginTransaction();
        try{
            map.put("id", id);
            Map obj = (Map) session.get(model, id);
            BeanUtil.beanToMap(map, obj, false, true);
            session.update(model, obj);

            transaction.commit();
        }catch (Exception e){
            transaction.rollback();
            e.printStackTrace();
        }
    }


    @Override
    public void delete(String model, String id){
        Transaction transaction = session.beginTransaction();
        try{
            Object obj = session.byId(model).load(id);
            session.delete(model, obj);

            transaction.commit();
        }catch (Exception e){
            transaction.rollback();
            e.printStackTrace();
        }
    }


}
